package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springdoc.core.service.GenericParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author 快点干早点散
 * @Create 2025/5/5 17:57
 * Description:
 */
@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IProductSkuService productSkuService;
    @Autowired
    private GenericParameterService parameterBuilder;
    @Autowired
    private ParameterNamesModule parameterNamesModule;
    @Autowired
    private IBrandService brandService;
    @Autowired
    private ISkuStockService skuStockService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductDetailsService productDetailsService;

    @Operation(summary = "首页数据")
    @GetMapping("/index")
    public AjaxResult indexData() {
        //1.创建首页V0对象分类
        IndexDataVo vo = new IndexDataVo();
        //2.封装一级分类列表
        List<CategoryVo> categoryVos = categoryService.getLevelOneCategory();
        vo.setCategoryList(categoryVos);

        //3.封装畅享TOP20商品列表
        List<ProductSkuVo> productSkuList = productSkuService.selectTopSale();
        vo.setProductSkuList(productSkuList);

        return AjaxResult.success(vo);
    }

    @Operation(summary = "查询所有分类")
    @GetMapping("/category")
    public AjaxResult categoryList() {
        List<CategoryVo> categoryVoList = categoryService.tree();
        return AjaxResult.success(categoryVoList);
    }

    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(
            @Parameter(description = "当前页码")
            @PathVariable Integer pageNum,
            @Parameter(description = "每页记录数")
            @PathVariable Integer pageSize,
            SkuQuery skuQuery) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductSkuVo> list = productSkuService.selectSkuList(skuQuery);
        return getDataTable(list);
    }


    //查询所有品牌
    @GetMapping("/brand")
    public AjaxResult selectBrandAll() {
        return success(brandService.list());

    }

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Schema(description = "返回商品详细信息")
    @GetMapping("/item/{skuId}")
    public AjaxResult item(@PathVariable("skuId") Long skuId) {

        //访问前判断是否存在
        //todo
        //1.创建 ItemVo 对象
        ItemVo itemVo = new ItemVo();
        //2.为ItemVo中七项属性逐一赋值
        //2.1根据商品id给商品赋值  异步返回结果:给商品轮播图,商品详情图 商品规格信息
        CompletableFuture<Long> productSkuCompletableFuture = CompletableFuture.supplyAsync(() -> {
            ProductSku productSku = productSkuService.getById(skuId);
            itemVo.setProductSku(productSku);
            return productSku.getProductId();
        }, threadPoolExecutor);

        //2.2获取商品价格  异步执行不需要上一次的返回值,也没有返回值
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            SkuPriceVo SkuPriceVo = productSkuService.getSkuPrice(skuId);
            itemVo.setSkuPrice(SkuPriceVo);
        }, threadPoolExecutor);

        //2.3获取商品的库存  异步执行不需要上一次的返回值,也没有返回值
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {
            SkuStockVo skuStockVo = skuStockService.getSkuStock(skuId);
            itemVo.setSkuStock(skuStockVo);
        }, threadPoolExecutor);

        //2.4获取商品轮播图 需要返回值但是没有返回结果
        CompletableFuture<Void> imageCompletableFuture = productSkuCompletableFuture.thenAcceptAsync(productId -> {
            Product product = productService.getById(productId);
            if (product != null && StringUtils.isNoneBlank(product.getSliderUrls())) {
                String sliderUrls = product.getSliderUrls();
                itemVo.setSliderUrlList(sliderUrls.split(","));
            }
            //2.5查询商品详情图片
            LambdaQueryWrapper<ProductDetails> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductDetails::getProductId, productId);
            ProductDetails productDetails = productDetailsService.getOne(queryWrapper);
            if (productDetails != null) {
                String imageUrls = productDetails.getImageUrls();
                itemVo.setDetailsImageUrlList(imageUrls.split(","));
            }
            //2.6商品规格信息
            String specValue = product.getSpecValue();
            if (StringUtils.isNoneBlank(specValue)) {
                JSONArray jsonArray = JSON.parseArray(specValue);
                itemVo.setSpecValueList(jsonArray);
            }
        }, threadPoolExecutor);

        //2.7封装商品规格参数跟SKUID映射关系Map{

        CompletableFuture<Void> skuSpecMapCompletableFuture = productSkuCompletableFuture.thenAcceptAsync(productId ->
                        itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId))
                , threadPoolExecutor);
        //3.阻塞线程,等待所有任务完成
        CompletableFuture.allOf(
                productSkuCompletableFuture,
                completableFuture,
                completableFuture1,
                imageCompletableFuture,
                skuSpecMapCompletableFuture
        ).join();
        return success(itemVo);
    }


}